import type { PageResponse, Result } from "./types"
import { CODE_MESSAGE_ZH } from "./interceptors"
import { useStore } from "@/hooks/useStore"

enum BASE_API_URL {
  DEVELOP = 'https://538g774y38.oicp.vip',
  TRIAL = 'https://oa.hmtflower.com',
  // TRIAL = 'https://oa.byteturing.com',
  RELEASE = 'http://172.20.10.3:8080/hhjbxt'
}

enum API_URL_PREFIX {
  COMMON = '/turing-service-system/api',
  CUSTOM = '/turing-service-business/busi'
}

// enum API_URL_PREFIX {
//   COMMON = "/api",
//   CUSTOM = "/busi",
// }

const BaseURL = BASE_API_URL.TRIAL
// const BaseURL = BASE_API_URL.DEVELOP;

type HasResponse<T> = T extends PageResponse ? any[] : T

// @ts-ignore
const successHandle = <T>({ data, statusCode }, resolve, reject) => {
  const tempData = data as Result<HasResponse<T>>

  if (statusCode >= 400 && Reflect.has(CODE_MESSAGE_ZH, statusCode)) {
    uni.showToast({
      title: CODE_MESSAGE_ZH[statusCode],
      icon: 'none'
    })
    reject(CODE_MESSAGE_ZH[statusCode])
    return
  }

  if (tempData.code < 400) {
    resolve(tempData)
  } else {
    if (tempData.code === 20011) {
      const { actionLogout } = useStore()
      actionLogout()
    }
    uni.showToast({
      title: tempData.msg,
      icon: 'none'
    })
    reject(tempData.msg)
  }
}

// @ts-ignore
const failHandle = (error, resolve, reject) => {
  uni.showToast({
    title: CODE_MESSAGE_ZH[504],
    icon: 'none'
  })
  reject(error)
}

const createRequest = (prefix: API_URL_PREFIX) => {
  return async <T = any>(params: UniApp.RequestOptions): Promise<Result<HasResponse<T>>> => {
    const { token } = useStore()
    return new Promise((resolve, reject) => {
      uni.request({
        url: BaseURL + prefix + params.url,
        data: params.data,
        header: {
          Accept: 'application/json',
          'Content-Type': 'application/json',
          'X-Requested-With': 'XMLHttpRequest',
          satoken: token,
          tenantId: 1,
          ...params.header
        },
        method: params.method,
        sslVerify: true,
        success: ({ data, statusCode, header }) => {
          successHandle<T>({ data, statusCode }, resolve, reject)
        },
        fail: (error) => {
          failHandle(error, resolve, reject)
        }
      })
    })
  }
}

const createdUploadRequest = (prefix: API_URL_PREFIX) => {
  return async <T = any>(params: UniApp.UploadFileOption): Promise<Result<HasResponse<T>>> => {
    const { token } = useStore()
    return new Promise((resolve, reject) => {
      uni.uploadFile({
        url: BaseURL + prefix + params.url,
        fileType: 'image',
        filePath: params.filePath,
        name: 'file',
        header: {
          satoken: token,
          ...params.header
        },
        success: ({ data, statusCode }) => {
          successHandle({ data: JSON.parse(data), statusCode }, resolve, reject)
        },
        fail: (error) => {
          failHandle(error, resolve, reject)
        }
      })
    })
  }
}

export const requestCommon = createRequest(API_URL_PREFIX.COMMON)

export const requestCustom = createRequest(API_URL_PREFIX.CUSTOM)

export const requestUpload = createdUploadRequest(API_URL_PREFIX.CUSTOM)
